package com.jin.service;

import java.util.Optional;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.jin.model.dto.UserInfoResponse;
import com.jin.model.dto.UserUpdateRequest;
import com.jin.model.dto.WechatLoginRequest;
import com.jin.model.dto.WechatLoginResponse;
import com.jin.model.dto.WechatSessionResponse;
import com.jin.model.entity.User;
import com.jin.repository.UserRepository;
import com.jin.util.JwtUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * 用户服务类
 */
@Slf4j
@Service
public class UserService {
    
    private final UserRepository userRepository;
    private final WechatService wechatService;
    private final JwtUtil jwtUtil;
    
    public UserService(UserRepository userRepository, WechatService wechatService, JwtUtil jwtUtil) {
        this.userRepository = userRepository;
        this.wechatService = wechatService;
        this.jwtUtil = jwtUtil;
    }
    
    /**
     * 微信登录
     */
    @Transactional
    public WechatLoginResponse wechatLogin(WechatLoginRequest request) {
        // 1. 通过code获取微信用户信息
        WechatSessionResponse sessionResponse = wechatService.code2Session(request.getCode());
        if (sessionResponse == null || !sessionResponse.isSuccess()) {
            throw new RuntimeException("微信登录失败：" + (sessionResponse != null ? sessionResponse.getErrMsg() : "获取用户信息失败"));
        }
        
        String openId = sessionResponse.getOpenId();
        String sessionKey = sessionResponse.getSessionKey();
        String unionId = sessionResponse.getUnionId();
        
        // 2. 查找或创建用户
        Optional<User> existingUser = userRepository.findByOpenId(openId);
        User user;
        boolean isNewUser = false;
        
        if (existingUser.isPresent()) {
            // 更新现有用户信息
            user = existingUser.get();
            user.setSessionKey(sessionKey);
            if (StringUtils.hasText(unionId)) {
                user.setUnionId(unionId);
            }
            // 更新用户资料（如果提供了新信息）
            updateUserProfile(user, request);
        } else {
            // 创建新用户
            user = createNewUser(openId, sessionKey, unionId, request);
            isNewUser = true;
        }
        
        user = userRepository.save(user);
        
        // 3. 生成JWT令牌
        String accessToken = jwtUtil.generateAccessToken(user.getId(), user.getOpenId());
        String refreshToken = jwtUtil.generateRefreshToken(user.getId(), user.getOpenId());
        
        // 4. 构建响应
        return WechatLoginResponse.builder()
                .userId(user.getId())
                .accessToken(accessToken)
                .refreshToken(refreshToken)
                .expiresIn(jwtUtil.getExpiration())
                .nickname(user.getNickname())
                .avatarUrl(user.getAvatarUrl())
                .creditPoints(user.getCreditPoints())
                .isNewUser(isNewUser)
                .build();
    }
    
    /**
     * 创建新用户
     */
    private User createNewUser(String openId, String sessionKey, String unionId, WechatLoginRequest request) {
        User user = new User();
        user.setOpenId(openId);
        user.setSessionKey(sessionKey);
        user.setUnionId(unionId);
        user.setNickname(request.getNickname());
        user.setAvatarUrl(request.getAvatarUrl());
        user.setGender(request.getGender());
        user.setCollege(request.getCollege());
        user.setGrade(request.getGrade());
        user.setCreditPoints(100); // 新用户赠送100学力值
        user.setStatus(0); // 正常状态
        
        log.info("Creating new user with openId: {}", openId);
        return user;
    }
    
    /**
     * 更新用户资料（只更新未自定义的字段）
     */
    private void updateUserProfile(User user, WechatLoginRequest request) {
        // 只有在用户未自定义昵称时，才用微信信息更新
        if (user.getNicknameCustomized() == 0 && StringUtils.hasText(request.getNickname())) {
            user.setNickname(request.getNickname());
        }

        // 只有在用户未自定义头像时，才用微信信息更新
        if (user.getAvatarCustomized() == 0 && StringUtils.hasText(request.getAvatarUrl())) {
            user.setAvatarUrl(request.getAvatarUrl());
        }

        // 只有在用户未自定义性别时，才用微信信息更新
        if (user.getGenderCustomized() == 0 && request.getGender() != null) {
            user.setGender(request.getGender());
        }

        // 学院和年级通常不从微信获取，所以这里不更新
        // 如果需要从微信更新，也要加上自定义标记的判断

        log.info("Updating user profile for openId: {} (only non-customized fields)", user.getOpenId());
    }
    
    /**
     * 根据ID获取用户
     */
    public Optional<User> getUserById(Long userId) {
        return userRepository.findById(userId);
    }
    
    /**
     * 根据openId获取用户
     */
    public Optional<User> getUserByOpenId(String openId) {
        return userRepository.findByOpenId(openId);
    }

    /**
     * 更新用户信息
     */
    @Transactional
    public UserInfoResponse updateUserInfo(Long userId, UserUpdateRequest request) {
        // 1. 查找用户
        Optional<User> userOptional = userRepository.findById(userId);
        if (userOptional.isEmpty()) {
            throw new RuntimeException("用户不存在");
        }

        User user = userOptional.get();

        // 2. 更新用户信息（只更新非空字段）并标记为已自定义
        if (StringUtils.hasText(request.getNickname())) {
            user.setNickname(request.getNickname());
            user.setNicknameCustomized(1); // 标记昵称已自定义
        }
        if (StringUtils.hasText(request.getAvatarUrl())) {
            user.setAvatarUrl(request.getAvatarUrl());
            user.setAvatarCustomized(1); // 标记头像已自定义
        }
        if (request.getGender() != null) {
            user.setGender(request.getGender());
            user.setGenderCustomized(1); // 标记性别已自定义
        }
        if (StringUtils.hasText(request.getCollege())) {
            user.setCollege(request.getCollege());
            user.setCollegeCustomized(1); // 标记学院已自定义
        }
        if (StringUtils.hasText(request.getGrade())) {
            user.setGrade(request.getGrade());
            user.setGradeCustomized(1); // 标记年级已自定义
        }

        // 3. 保存更新
        user = userRepository.save(user);

        log.info("User info updated for userId: {} (marked as customized)", userId);

        // 4. 返回更新后的用户信息
        return convertToUserInfoResponse(user);
    }

    /**
     * 获取用户详细信息
     */
    public UserInfoResponse getUserInfo(Long userId) {
        Optional<User> userOptional = userRepository.findById(userId);
        if (userOptional.isEmpty()) {
            throw new RuntimeException("用户不存在");
        }

        return convertToUserInfoResponse(userOptional.get());
    }

    /**
     * 将User实体转换为UserInfoResponse
     */
    private UserInfoResponse convertToUserInfoResponse(User user) {
        return UserInfoResponse.builder()
                .userId(user.getId())
                .nickname(user.getNickname())
                .avatarUrl(user.getAvatarUrl())
                .gender(user.getGender())
                .college(user.getCollege())
                .grade(user.getGrade())
                .creditPoints(user.getCreditPoints())
                .status(user.getStatus())
                .createdAt(user.getCreatedAt())
                .updatedAt(user.getUpdatedAt())
                .build();
    }
}
